<template>
  <div id="app">
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary shadow-sm">
      <div class="container">
        <router-link to="/" class="navbar-brand">
          <i class="bi bi-shop me-2"></i>在线商城
        </router-link>

        <button
            class="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarNav"
        >
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav me-auto">
            <li class="nav-item">
              <router-link to="/products" class="nav-link">
                <i class="bi bi-grid me-1"></i>商品
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/cart" class="nav-link">
                <i class="bi bi-cart me-1"></i>购物车
                <span v-if="cartCount > 0" class="badge bg-danger ms-1">
                  {{ cartCount }}
                </span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/orders" class="nav-link">
                <i class="bi bi-receipt me-1"></i>订单
              </router-link>
            </li>

            <!-- 管理员菜单 -->
            <li v-if="isAdmin" class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="adminDropdown" role="button" data-bs-toggle="dropdown">
                <i class="bi bi-gear me-1"></i>管理
              </a>
              <ul class="dropdown-menu">
                <li>
                  <router-link to="/admin/products" class="dropdown-item">
                    商品管理
                  </router-link>
                </li>
              </ul>
            </li>

            <!-- 卖家菜单 -->
            <li v-if="isSeller" class="nav-item">
              <router-link to="/seller/orders" class="nav-link">
                <i class="bi bi-box-seam me-1"></i>卖家中心
              </router-link>
            </li>
          </ul>

          <div class="d-flex align-items-center">
            <!-- 登录状态 -->
            <template v-if="isAuthenticated">
              <div class="dropdown">
                <a
                    class="text-white text-decoration-none dropdown-toggle"
                    href="#"
                    id="userDropdown"
                    data-bs-toggle="dropdown"
                >
                  <i class="bi bi-person-circle me-1"></i>
                  {{ username }}
                  <span class="badge bg-light text-dark ms-2">
                    {{ roleText }}
                  </span>
                </a>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li>
                    <router-link to="/profile" class="dropdown-item">
                      <i class="bi bi-person me-2"></i>个人资料
                    </router-link>
                  </li>
                  <li><hr class="dropdown-divider"></li>
                  <li>
                    <button class="dropdown-item text-danger" @click="logout">
                      <i class="bi bi-box-arrow-right me-2"></i>退出登录
                    </button>
                  </li>
                </ul>
              </div>
            </template>

            <!-- 未登录状态 -->
            <template v-else>
              <router-link to="/login" class="btn btn-outline-light me-2">
                登录
              </router-link>
              <router-link to="/register" class="btn btn-light">
                注册
              </router-link>
            </template>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主内容区 -->
    <main class="container py-4">
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in">
          <component :is="Component" />
        </transition>
      </router-view>
    </main>

    <!-- 页脚 -->
    <footer class="bg-light py-4 mt-5 border-top">
      <div class="container text-center text-muted">
        <p>© 2023 在线商城系统 - 课程设计项目</p>
        <p class="mb-0">前端: Vue.js | 后端: Spring Boot | 数据库: MySQL</p>
      </div>
    </footer>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { cartApi } from '@/api'

export default {
  name: 'App',
  setup() {
    const router = useRouter()

    // 用户状态
    const username = ref('')
    const userId = ref('')
    const userRole = ref('')

    // 购物车数量
    const cartCount = ref(0)

    // 计算属性
    const isAuthenticated = computed(() => {
      return !!userId.value
    })

    const isAdmin = computed(() => {
      return userRole.value === 'ADMIN'
    })

    const isSeller = computed(() => {
      return userRole.value === 'SELLER'
    })

    const roleText = computed(() => {
      const roles = {
        'ADMIN': '管理员',
        'SELLER': '卖家',
        'BUYER': '买家'
      }
      return roles[userRole.value] || '用户'
    })

    // 加载用户信息
    const loadUserInfo = () => {
      username.value = localStorage.getItem('username') || ''
      userId.value = localStorage.getItem('userId') || ''
      userRole.value = localStorage.getItem('role') || ''
    }

    // 加载购物车数量
    const loadCartCount = async () => {
      if (!userId.value) {
        cartCount.value = 0
        return
      }

      try {
        // 使用正确的API获取购物车项
        const cartItems = await cartApi.getByUser(userId.value)
        // 计算商品总数（考虑每项的数量）
        cartCount.value = cartItems.reduce((total, item) => total + item.quantity, 0)
      } catch (error) {
        console.error('加载购物车数量失败:', error)
        cartCount.value = 0
      }
    }

    // 退出登录
    const logout = () => {
      // 清除本地存储
      localStorage.removeItem('username')
      localStorage.removeItem('userId')
      localStorage.removeItem('role')

      // 重置状态
      username.value = ''
      userId.value = ''
      userRole.value = ''
      cartCount.value = 0

      // 重定向到首页
      router.push('/')
    }

    // 初始化
    onMounted(() => {
      loadUserInfo()
      if (isAuthenticated.value) {
        loadCartCount()
      }
    })

    // 监听路由变化更新用户信息
    router.afterEach(() => {
      loadUserInfo()
      if (isAuthenticated.value) {
        loadCartCount()
      }
    })

    // 监听userId变化自动更新购物车
    watch(userId, (newVal) => {
      if (newVal) {
        loadCartCount()
      } else {
        cartCount.value = 0
      }
    })

    return {
      username,
      userId,
      userRole,
      cartCount,
      isAuthenticated,
      isAdmin,
      isSeller,
      roleText,
      logout
    }
  }
}
</script>

<style scoped>
#app {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

main {
  flex: 1;
}

.navbar {
  position: sticky;
  top: 0;
  z-index: 1000;
}

/* 路由切换动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>